﻿using lin_cms_dotnet_core.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace lin_cms_dotnet_core.Controllers.cms
{
    [Route("cms/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private JwtSettings _jwtSettings;

        public UserController(IOptions<JwtSettings> _jwtSettingsAccesser)
        {
            _jwtSettings = _jwtSettingsAccesser.Value;
        }

        [Route("login")]
        [HttpPost]
        public string login([FromBody] LinUser user)
        {
            var claims = new Claim[]{
            new Claim(ClaimTypes.Name,user.Username)
        };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(_jwtSettings.Issuer,
                _jwtSettings.Audience,
                claims,
                DateTime.Now,
                DateTime.Now.AddSeconds(10),
                creds);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
